package com.bwc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwc.common.BussinessException;
import com.bwc.dao.SetmealDao;
import com.bwc.domain.Category;
import com.bwc.domain.DishFlavor;
import com.bwc.domain.Setmeal;
import com.bwc.domain.SetmealDish;
import com.bwc.dto.SetmealDto;
import com.bwc.service.CategoryService;
import com.bwc.service.SetmealDishService;
import com.bwc.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithSetmealDish(SetmealDto setmealDto) {

        this.save(setmealDto);
        Long setmealId = setmealDto.getId();

        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();

        setmealDishList=setmealDishList.stream().map((item)->{
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishList);


    }

    @Override
    @Transactional
    public void moveWithDish(List<Long> ids) {

        //select count（*） from setmeal where id in ids and status = 1
        //如果套餐是在起售的状态，那么则不可以删除套餐，同时抛出一个异常，让全局异常处理器捕获
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus, 1);

        Integer count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            //抛出一个业务错误
            throw new BussinessException("不能删除处于启售的套餐");
        }

        this.removeByIds(ids);

        //删除setmeal_dish表中的数据
        //delete from setmeal_dish where setmealId in ids
        LambdaQueryWrapper<SetmealDish> l2 = new LambdaQueryWrapper<>();
        l2.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(l2);
    }

}
